package actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;

import document.AwesomeDocument;
import document.SyntaxHighlighter;

import awesomeDocumentIO.AwesomeDocumentImporter;

import textArea.AwesomeTextPanel;
import frame.AwesomeFrame;

import misc.Vals;
/**
 * Creates the visual interface for opening a new document.
 * @author Brittin
 *
 */
public class OpenFileAction extends AwesomeMenuAction {

	public OpenFileAction(String name, String desc) {
		super(name, desc);
		putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_O));
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		JFileChooser fc = this.getFileChooser(e);

		if (fc == null)
			return;

		// Open the file dialog
		int retVal = fc.showOpenDialog(this.getParentFrame(e));

		// If the user selects a file
		if (retVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			
			AwesomeTextPanel panel = this.getSelectedTextPanel(e);
			AwesomeFrame frame = this.getParentFrame(e);
			
			// Prompt them to save the older file if one is open and it is not
			// yet saved
			JTextPane selectedTextPane = this.getSelectedTextPane(e);
			if (panel.isChanged()) {
				int response = JOptionPane.showConfirmDialog(null,
						Vals.saveChangesMessage);
				if (response == JOptionPane.OK_OPTION) {
					File oldfile = frame.getCurrentFile();
					try {
						// Write the old file
						ActionFileIO.saveFile(oldfile, panel.getTextPane().getText());

					} catch (IOException ex) {
						JOptionPane.showMessageDialog(null,
								Vals.fileWriteErrorMessage);
						// e.printStackTrace();
					}

				} else if (response == JOptionPane.CANCEL_OPTION) {
					return;
				}
			}

			// Get the extension of that file.
			String extension = file.getName();
			extension = extension.substring(extension.lastIndexOf('.') + 1);
			extension = extension.trim();
			
			// If the extension exists in the extensions library
			// Format the text pane accordingly
			HashMap<String, String> docinfo = AwesomeDocumentImporter.getAllDocInfo();
			
				
			try {
				// Read in the file
				BufferedReader reader = new BufferedReader(new FileReader(file));
				StringBuilder sb = new StringBuilder();
				String line = null;

				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}

				reader.close();

				// Set the text
				selectedTextPane.setText(sb.toString());
				
				//do formatting
				if (docinfo.containsValue(extension))
				{
					String label = null;
					for( String str : docinfo.keySet() ){
						
						if(docinfo.get(str).equals(extension)) {
							label = str;
							break;
						}
					}
					
					AwesomeDocument doc = AwesomeDocumentImporter.importDocumentType(label);
					panel.setDocumentType(doc);
					frame.setTitle(Vals.mainFrameTitle + ": " + file.getName());
					SyntaxHighlighter.highlightDocument(selectedTextPane, doc);
				} else {
					panel.setDocumentType(null);
				}
				panel.setChanged(false);
			} catch (IOException ex) {
				System.err.println(e);
				return;
			}

		} else {
			return;
		}

	}

}
